"""
Copyright © 2024 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/ibizsim-onekey-input
"""
from pynput import mouse
from pynput import keyboard
from pynput.keyboard import Key, Controller
import pyperclip
from time import sleep


ctrl_pressed = False
terminate_loop = False
send_duration = 0.1

keyboard_controller = Controller()

def parse_and_send_excel_data():
	global terminate_loop

	cells_data = []
	skip_title = True
	data_index = { # {row: (index, count)}
		1:  (1, 5),  2: (1, 5),  3: (1, 5),  4: (1, 5), 5: (1, 4),
		7:  (1, 4),  8: (1, 4),  9: (1, 4), 10: (1, 4),
		12: (1, 5), 13: (1, 5), 14: (1, 5), 15: (1, 5),
		17: (0, 4),
		19: (0, 5),
	}

	for data in pyperclip.paste().split('\r\n'):
		cells_data.append(list(filter(lambda x: x != '', data.split('\t'))))
	# print(cells_data)

	if cells_data[0][0] == '完成决策':
		skip_title = False

	for row, data in data_index.items():
		row += 1 if not skip_title else 0

		for column in range(data[1]):
			if terminate_loop:
				terminate_loop = False
				return

			pyperclip.copy(cells_data[row][column + data[0]])

			keyboard_controller.press(Key.ctrl)
			keyboard_controller.press('v')
			keyboard_controller.release('v')
			keyboard_controller.release(Key.ctrl)
			sleep(send_duration)

			keyboard_controller.press(Key.tab)
			keyboard_controller.release(Key.tab)
			sleep(send_duration)

			# print(f'{cells_data[row][column + data[0]]}', end=', ')
		# print()

# region mouse and keyboard events
def on_click(x, y, button, pressed):
	global ctrl_pressed

	if not pressed: # mouse button released
		if ctrl_pressed and button == mouse.Button.left:
			sleep(0.1)

			with keyboard_controller.pressed(Key.ctrl):
				keyboard_controller.type('a')

			try:
				parse_and_send_excel_data()
			except Exception as ex:
				print('parse_and_send_excel_data() failed, error:', ex)

def on_press(key):
	global ctrl_pressed

	if not ctrl_pressed:
		ctrl_pressed = key == Key.ctrl_l

	# print(f'{key} pressed, alt: {_alt_pressed}')

def on_release(key):
	global ctrl_pressed, terminate_loop

	if key == Key.esc:
		terminate_loop = True

	if ctrl_pressed and key == Key.ctrl_l:
		ctrl_pressed = not ctrl_pressed

	# print(f'{key} released, alt: {_alt_pressed}')
# endregion

mouse_listener    = mouse.Listener(on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)


if __name__ == '__main__':
	mouse_listener.start()
	keyboard_listener.start()

	try:
		while True:
			sleep(0.1)
	except KeyboardInterrupt:
		pass
